package com.cloudshadow.platform.server.common.base.service;


import com.cloudshadow.platform.infrastructure.core.service.CoreService;
import com.cloudshadow.platform.server.common.base.dao.BaseDao;
import com.cloudshadow.platform.server.common.base.model.BaseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;

import java.io.Serializable;
import java.util.List;

public abstract class BaseServiceImpl<Dao extends BaseDao<T,K>, T extends BaseModel, K extends Serializable> extends CoreService
        implements BaseService<Dao, T, K> {

    @Autowired
    private Dao dao;

    @Override
    public List<T> findAll() {
        return dao.findAll();
    }

    @Override
    public List<T> findAll(T entity) {
        return dao.findAll(Example.of(entity));
    }

    @Override
    public Page<T> findByPage(T entity, Integer page, Integer size, Sort sort) {
        Pageable pageable = new PageRequest(page - 1, size, sort);
        ExampleMatcher macher = ExampleMatcher.matching();
        Example<T> example = Example.of(entity, macher);
        return dao.findAll(example, pageable);
    }

    @Override
    public T findOneByID(K id) {
        return dao.findOne(id);
    }

    @Override
    public T save(T entity) {
        return dao.save(entity);
    }

    @Override
    public void delete(K id){
        dao.delete(id);
    }


    @Override
    public T getOne(T entity) {
        Example<T> example = Example.of(entity);
        Page<T> page = dao.findAll(example, new PageRequest(0, 1));
        List<T> list = page.getContent();
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

}
